package com.nzy.ssm.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.nzy.ssm.base.BaseController;
import com.nzy.ssm.entity.Seller;
import com.nzy.ssm.service.ISellerService;
import com.nzy.ssm.util.Pager;
import com.nzy.ssm.util.ResultUtil;
import com.nzy.ssm.util.UUIDUtils;

@Controller
@RequestMapping("seller")
public class SellerController extends BaseController {

	@Autowired
	private ISellerService sellerService;
	
	@RequestMapping("/register")
	public String toSellerReg() {
		return "/seller/res";
	}
	
	@RequestMapping("/slogin")
	public String tosLogin() {
		return "/seller/slogin";
	}
	
	
	/** 执行商家用户注册 */
	@RequestMapping("/toSRes")
	@ResponseBody
	public ResultUtil toSRes(Seller seller, @RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request)
			throws IOException {
		if (files.length > 0 && files[0].getSize() > 0) {
			for (int s = 0; s < files.length; s++) {
				String n = UUIDUtils.create();
				String path = request.getServletContext().getRealPath("/") + "/resources/ueditor/upload/" + n
						+ files[s].getOriginalFilename();
				File newFile = new File(path);
				files[s].transferTo(newFile);
				if (s == 0) {
					seller.setBusiness(request.getContextPath() + "/resources/ueditor/upload/" + n
							+ files[s].getOriginalFilename());
				}
			}
		}else {
			return ResultUtil.error("请提交营业执照");
		}
		seller.setState("2");
		int i = sellerService.insert(seller);
		if (i > 0) {
			return ResultUtil.ok();
		}
		return ResultUtil.error("申请失败");
	}
	
	
	/**
	 * 	商家列表
	 * @param model
	 * @param seller
	 * @return
	 */
	@RequestMapping("/findSeller")
	public String findSeller(Model model, Seller seller) {
		String sql = "select * from seller where 1=1 ";
		if (!isEmpty(seller.getSellerName())) {
			sql += " and sellerName like '%" + seller.getSellerName() + "%' ";
		}
		sql += " order by id";
		Pager<Seller> pagers = sellerService.findBySqlRerturnEntity(sql);
		model.addAttribute("pagers", pagers);
		model.addAttribute("obj", seller);
		return "seller/seller";
	}
	
	
}
